package com.leyou.auth.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.auth.config.OssProperties;
import com.leyou.auth.dto.AliOssSignatureDTO;
import com.leyou.auth.service.AliAuthService;
import com.leyou.common.exceptions.LyException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 生成OSS的文件签名
 * 将阿里云提供的签名信息优化：
 * - 1.把字符串常量抽取到yaml文件
 * - 2.把OSS的客户端抽取并注入spring
 * - 3.改造返回值部分，用DTO代替map
 */
@Service
@Slf4j
public class AliAuthServiceImpl implements AliAuthService {
    @Resource
    private OSS ossClient;
    @Resource
    private OssProperties prop;
    @Override
    public AliOssSignatureDTO getSignature() {

        try {
            // 过期时间
            long expireTime = prop.getExpireTime();
            long expireEndTime = System.currentTimeMillis() + expireTime;
            Date expiration = new Date(expireEndTime);
            // 上传策略条件
            PolicyConditions policyConds = new PolicyConditions();
            // 文件大小限制
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, prop.getMaxFileSize());
            // 文件目录限制
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, prop.getDir());
            // 对策略加密
            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            // 生成签名
            String postSignature = ossClient.calculatePostSignature(postPolicy);
            // 响应结果,封装成DTO
            return AliOssSignatureDTO.of(prop.getAccessKeyId()
                    , prop.getHost()
                    , encodedPolicy
                    , postSignature
                    , expireEndTime
                    , prop.getDir()
            );
        } catch (Exception e) {
            log.error("上传文件失败，原因：{}", e.getMessage(), e);
            throw new LyException(500, "生成授权签名失败!",e);
        }
    }
}
